#!/bin/bash

# 部署脚本路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $SCRIPT_DIR/..
git pull

function deployService() {
  echo "部署后端服务"
  APP_NAME="yilan-chat-server-app"
  mvn clean install -DskipTests=true

  if docker ps -a | grep -q ${APP_NAME}; then
    docker stop ${APP_NAME}
    docker rm ${APP_NAME}
    docker rmi ${APP_NAME}
  fi

  cp target/yilan-chat-server-app.jar deploy/yilan-chat-server-app.jar
  cd deploy
  docker build -t ${APP_NAME} .
  docker run -d --name ${APP_NAME} --restart always \
    -p 18086:18086 \
    -e "SPRING_PROFILES_ACTIVE=test" \
    ${APP_NAME}
  rm -rf yilan-chat-server-app.jar
}

function uploadInterfaceDoc() {
  echo '更新接口文档'
  cd $SCRIPT_DIR/..
  mvn -Dfile.encoding=UTF-8 smart-doc:torna-rest
}

function deployWeb() {
    echo "部署前端服务"
    cd $SCRIPT_DIR/web
    rm -rf dist
    unzip dist.zip
    APP_NAME="vtm-web"

    if docker ps -a | grep -q ${APP_NAME}; then
        docker stop ${APP_NAME}
        docker rm ${APP_NAME}
        docker rmi ${APP_NAME}
    fi

    docker build -t ${APP_NAME} .
    docker run --name ${APP_NAME} -d -p 18088:80 -p 433:433 \
        -v ${SCRIPT_DIR}/web/nginx.conf:/etc/nginx/nginx.conf ${APP_NAME}
}

while getopts ":sihw" opt; do
  case $opt in
    s)
      deployService
      ;;
    i)
      uploadInterfaceDoc
      ;;
    h)
      echo "请输入参数："
      echo "-s：部署后端服务"
      echo "-i：更新接口文档"
      ;;
    w)
      deployWeb
      ;;
    \?)
      echo "无效的选项: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "选项 -$OPTARG 需要一个参数." >&2
      exit 1
      ;;
  esac
done